package lc.com.lcpicturebackend.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lc.com.lcpicturebackend.api.deepseek.model.DeepSeekApi;
import lc.com.lcpicturebackend.exception.BusinessException;
import lc.com.lcpicturebackend.exception.ErrorCode;
import lc.com.lcpicturebackend.exception.ThrowUtils;
import lc.com.lcpicturebackend.mapper.ConversationMapper;
import lc.com.lcpicturebackend.model.dto.chatai.ConversationAddRequest;
import lc.com.lcpicturebackend.model.dto.chatai.ConversationQueryRequest;
import lc.com.lcpicturebackend.model.entity.Conversation;
import lc.com.lcpicturebackend.model.entity.User;
import lc.com.lcpicturebackend.service.ConversationMsgService;
import lc.com.lcpicturebackend.service.ConversationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @author 罗超
 * @description 针对表【conversation】的数据库操作Service实现
 * @createDate 2025-05-26 22:02:24
 */
@Service
@Slf4j
public class ConversationServiceImpl extends ServiceImpl<ConversationMapper, Conversation>
        implements ConversationService {


    @Resource
    private DeepSeekApi deepSeekApi;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private ConversationMsgService conversationMsgService;


    @Override
    @Async
    public void createConversation(ConversationAddRequest conversationAddRequest, User loginUser) {
        // 1. 参数校验
        validateRequest(conversationAddRequest, loginUser);

        // 2. 检查会话是否已存在
        if (conversationExists(conversationAddRequest.getConversationId())) {
            return;
        }

        // 3. 生成标题
        String title = generateConversationTitle(conversationAddRequest);

        // 4. 创建并保存会话
        saveConversation(conversationAddRequest.getConversationId(), title, loginUser.getId());
    }

    @Override
    public QueryWrapper<Conversation> getQueryWrapper(ConversationQueryRequest conversationQueryRequest,Long userId) {
        QueryWrapper<Conversation> conversationQueryWrapper = new QueryWrapper<>();

        String sortField = conversationQueryRequest.getSortField();
        String sortOrder = conversationQueryRequest.getSortOrder();

        if (userId == null || userId < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        conversationQueryWrapper.eq("userId", userId);
        conversationQueryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("descend"), sortField);
        return conversationQueryWrapper;
    }

    @Override
    public void deleteConversation(String conversationId, User loginUser) {
        // 判断数据库中是否存在
        Conversation oldConversation = this.getById(conversationId);
        ThrowUtils.throwIf(ObjectUtil.isEmpty(oldConversation), ErrorCode.NOT_FOUND_ERROR);

        // 判断是否有权限
        if (!oldConversation.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        // 删除会话
        boolean remove = this.removeById(conversationId);
        ThrowUtils.throwIf(!remove, ErrorCode.SYSTEM_ERROR, "删除会话失败");

        // 操作会话消息
        conversationMsgService.deleteConversationMsg(conversationId);
    }

    /**
     * 验证请求参数
     */
    private void validateRequest(ConversationAddRequest request, User user) {
        if (request == null || user == null || user.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数或用户信息不能为空");
        }
        if (StrUtil.isBlank(request.getConversationId())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "会话ID不能为空");
        }
    }

    /**
     * 检查会话是否已存在
     */
    private boolean conversationExists(String conversationId) {
        return this.lambdaQuery()
                .eq(Conversation::getConversationId, conversationId)
                .exists();
    }

    /**
     * 生成会话标题
     */
    private String generateConversationTitle(ConversationAddRequest request) {
        // 优先使用API生成标题
        if (StrUtil.isNotBlank(request.getContent())) {
            try {
                return deepSeekApi.getChatResponse(request.getContent());
            } catch (Exception e) {
                log.error("调用deepseek服务失败：{}", e.getMessage());
                // 失败后降级处理
            }
        }

        // 次优先使用请求中的标题，最后使用默认标题
        return StrUtil.isNotBlank(request.getTitle()) ? request.getTitle() : "新对话";
    }

    /**
     * 保存会话
     */
    private void saveConversation(String conversationId, String title, Long userId) {
        Conversation conversation = new Conversation();
        conversation.setConversationId(conversationId);
        conversation.setTitle(title);
        conversation.setUserId(userId);
        if (!this.save(conversation)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "创建会话失败");
        }
    }
}




